package com.example.itrain.demo.auth;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.itrain.demo.model.User;
import com.example.itrain.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 在这里实现从数据库或其他存储加载用户
        if (StringUtils.isNotEmpty(username)) {
            User accountUser = userService.list(Wrappers.<User>lambdaQuery().eq(User::getAccountName, username)).stream().findFirst().orElse(null);
            if (ObjectUtils.isEmpty(accountUser)) {
                throw new UsernameNotFoundException("User not found: " + username);
            }
            // 构建 UserDetails 对象
            return org.springframework.security.core.userdetails.User.builder().username(accountUser.getAccountName()).password(accountUser.getAccountPassword()) // 加密密码
//                    .authorities(accountUser.getRoles().split(",")) // 将角色字符串拆分为数组
                    .authorities("admin") // 将角色字符串拆分为数组
                    .build();
        }
        throw new UsernameNotFoundException("username can not be empty");
    }
}
